package com.cysoft.dao;

import com.cysoft.domain.Mold;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author andaolong
 * @time 2021年3月27日11:23:11
 * 从数据库中获取数据
 */
@Component
public class MoldDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    //查询所有的device的id，返回device类型的list，里面还未填入machiningType
    public List<Mold> getMoldListFromDB() {

        //首先查询到所有的device_id
        String sql = "select * from mold";
        //将查询到的所有device_id存到一串<Machine>的list里面
        //return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Machine.class));

        //调试用
        //List<Machine> deviceList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Machine.class));
        //for(Machine device:deviceList){
        //    System.out.println("deviceDao获取到的deviceId为："+device.getDeviceId());
        //}
        //return deviceList;

        //给从数据库中获得的device添加上id，排程的时候需要依靠这个id进行移动操作
        List<Mold> moldList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Mold.class));

        return moldList;
    }

    public List<Mold> getMoldListByWheelCode(String code) {

        //首先查询到所有的device_id
        String sql = "select * from mold where wheel_code = '" + code + "' and type=1 order by name desc";
        String sql2 = "select * from mold where wheel_code = '" + code + "' and type=0 order by name desc";

        //给从数据库中获得的device添加上id，排程的时候需要依靠这个id进行移动操作
        List<Mold> moldList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Mold.class));
        List<Mold> moldList2 = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(Mold.class));
        Set<Mold> matchMoldList = new HashSet<>();
        for (Mold mold2 : moldList2) {
            for (Mold mold1 : moldList) {
                if(mold1.getName().equals(mold2.getName())) {
                    matchMoldList.add(mold1);
                }
            }
        }
        matchMoldList.addAll(moldList2);

        List<Mold> newMoldList = new ArrayList<Mold>();
        newMoldList.addAll(matchMoldList);
        newMoldList.sort(new Comparator<Mold>() {
            @Override
            public int compare(Mold o1, Mold o2) {
                int comp = (o1.getName().compareTo(o2.getName()));
//                if(comp > 0) {
//                    return -1;
//                } else if (comp <0) {
//                    return 1;
//                }
                return comp;
            }
        });
        return newMoldList;
    }


}
